package com.dashu.authority.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dashu.authority.common.Constant;
import com.dashu.authority.entity.User;
import com.dashu.authority.exception.AuthorityException;
import com.dashu.authority.servie.UserAndRoleService;
import com.dashu.authority.servie.UserService;
import com.dashu.authority.util.ResultBean;
import com.dashu.authority.util.ResultMsgUtil;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Resource
	private UserService userService;
	@Resource
	private UserAndRoleService userAndRoleService;

	@RequestMapping("/findAllByPaging")
	public @ResponseBody Object findAllByPaging(User entity, Integer page, Integer rows) throws AuthorityException {
		List<User> returnList = userService.queryAllByExample(entity, page, rows);
		Map<String, Object> returnMap = ResultMsgUtil.datagridFormat(new PageInfo<User>(returnList));
		return new ResultBean(Constant.STATUS_NORMAL, returnMap).getResultMap();
	}

	@RequestMapping(value = "/save")
	public @ResponseBody Object addUser(User entity) throws AuthorityException {
		Map<String, Object> returnMap = userService.insertEntity(entity);
		return new ResultBean(returnMap).getResultMap();
	}

	@RequestMapping(value = "/update")
	public @ResponseBody Object updateUser(User entity) throws AuthorityException {
		Map<String, Object> returnMap = userService.updateEntity(entity);
		return new ResultBean(returnMap).getResultMap();
	}

	@RequestMapping(value = "/deleteByIds")
	public @ResponseBody Object deleteByIds(@RequestParam(value = "ids") Integer[] ids) throws AuthorityException {
		Map<String, Object> returnMap = userService.deleteByIds(ids);
		return new ResultBean(returnMap).getResultMap();
	}

	@RequestMapping(value = "/updateStatus")
	public @ResponseBody Object updateStatus(@RequestParam(value = "ids") Integer[] ids, String status)
			throws AuthorityException {
		Map<String, Object> returnMap = userService.updateStatus(ids, status);
		return new ResultBean(returnMap).getResultMap();
	}

	@RequestMapping(value = "/saveUserAndRole")
	public @ResponseBody Object addUser(Integer userId, String roleIds) throws AuthorityException {
		Integer[] ids;
		if (roleIds == null || "".equals(roleIds)) {
			ids = new Integer[0];
		} else {
			String[] re = roleIds.split(",");
			ids = new Integer[re.length];
			if (re != null && re.length > 0) {
				for (int i = 0; i < re.length; i++) {
					ids[i] = Integer.valueOf(re[i]);
				}
			}
		}
		Map<String, Object> returnMap = userAndRoleService.saveAll(userId, ids);
		return new ResultBean(returnMap).getResultMap();
	}
}
